import cv2
import numpy as np

jump = cv2.imread("images/jump_1.png", cv2.IMREAD_GRAYSCALE)
jump=cv2.resize(jump,None,fx=0.5, fy=0.5, interpolation = cv2.INTER_CUBIC)
qizi_temp = cv2.imread("templates/qi_zi_temp.png", cv2.IMREAD_GRAYSCALE)
w, h = qizi_temp.shape[::-1]

# 计算棋子位置
res = cv2.matchTemplate(jump, qizi_temp, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
x1 = int(top_left[0] + 20)
y1 = int(top_left[1] + 67)
#print(x1, y1)

# 计算目标位置
# 1.高斯滤波(有利于边缘提取)
jump = cv2.GaussianBlur(jump, (5, 5), 0)
# 2.边缘提取
canny = cv2.Canny(jump, 1, 10)

# 3.去掉小棋子的影响
for row in range(top_left[1],top_left[1]+h):
    for col in range(top_left[0],top_left[0]+w):
        canny[row][col]=0

# 3.从200行开始向下扫描找到值为1的行
y2_top = np.nonzero([row for row in canny[200:]])[0][0] + 200

# 4.在上述行上向右扫描找到值为1的列
x2_top = int(np.mean(np.nonzero(canny[y2_top])))
#print(x2_top, y2_top)
x2=x2_top

# 5.在上述列+100下向上扫描找到值为1的行
#y2_bottom = y2_top+100-np.nonzero(canny[y2_top + 100::-1, x2_top])[0][0]
y2_bottom = np.nonzero(canny[y2_top+1::, x2_top])[0][0]+y2_top+1
y2 = (y2_bottom + y2_top) / 2

cv2.namedWindow("test",cv2.WINDOW_AUTOSIZE)
cv2.rectangle(canny, top_left, bottom_right, 255, 2)
cv2.line(canny,(int(x2_top),int(y2_top)),(int(x2_top),int(y2_bottom)),255,2)
cv2.line(canny,(int(x1),int(y1)),(int(x2),int(y2)),255,2)
cv2.imshow("test",canny)

cv2.waitKey()
cv2.destroyAllWindows()
print((x1,y1),(x2,y2),((x2-x1)**2+(y2-y1)**2)**0.5)
#返回2点之间的距离